<template>
  <div>
    <el-dialog
      :before-close="cancel"
      :title="info.isAdd?'添加商品分类':'编辑商品分类'"
      :visible.sync="info.isShow"
      center
      @opened="openEvent"
    >
      <!-- 一级分类 -->
      <el-form ref="goods" :model="goodsinfo" :rules="rules">
        <el-form-item prop="first_cateid" label="一级分类" :label-width="formLabelWidth">
          <el-select @change="changeCate(false)" v-model="goodsinfo.first_cateid" placeholder="请选择">
            <el-option disabled label="请选择分类" :value="0"></el-option>
            <el-option
              v-for="item in catelist"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 二级分类 -->
        <el-form-item prop="second_cateid" label="二级分类" :label-width="formLabelWidth">
          <el-select v-model="goodsinfo.second_cateid" placeholder="请选择">
            <el-option disabled label="请选择分类" :value="0"></el-option>
            <el-option
              v-for="item in secondArr"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 输入框 -->
        <el-form-item prop="goodsname" label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="goodsinfo.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input v-model="goodsinfo.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="market_price" label="市场价格" :label-width="formLabelWidth">
          <el-input v-model="goodsinfo.market_price" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="图片" :label-width="formLabelWidth">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onpreview"
            :on-remove="onremove"
            :auto-upload="false"
            :on-change="onchange"
            :limit="1"
            :file-list="filelist"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品规格 -->
        <el-form-item prop="specsid" label="商品规格" :label-width="formLabelWidth">
          <el-select @change="changeSpecs(false)" v-model="goodsinfo.specsid" placeholder="请选择">
            <el-option disabled label="请选择分类" :value="0"></el-option>
            <el-option
              v-for="item in specslist"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 规格属性 -->
        <el-form-item prop="specsattr" label="规格属性" :label-width="formLabelWidth">
          <el-select multiple v-model="goodsinfo.specsattr" placeholder="请选择">
            <!-- <el-option disabled label="请选择分类" :value="0"></el-option> -->
            <el-option v-for="item in specsArr" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 是否新品 -->
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="goodsinfo.isnew" :label="1">是</el-radio>
          <el-radio v-model="goodsinfo.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="goodsinfo.ishot" :label="1">是</el-radio>
          <el-radio v-model="goodsinfo.ishot" :label="2">否</el-radio>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-switch
            v-model="goodsinfo.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <!-- 描述 -->
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="editor"></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsadd, goodsedit, goodsinfo } from "../../request/api";
import { mapGetters, mapActions } from "vuex";
import E from "wangeditor";
export default {
  data() {
    return {
      goodsinfo: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1
      },
      secondArr: [],
      specsArr: [],
      dialogVisible: false,
      dialogImageUrl: "",
      filelist: [], //用于图片回显
      editor: null,
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur"
          }
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" }
        ],
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" }
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "blur" }
        ],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" }
        ],
        specsattr: [
          { required: true, message: "请选择规格属性", trigger: "blur" }
        ]
      },
      formLabelWidth: "120px"
    };
  },
  computed: {
    ...mapGetters({
      catelist: "cate/getCate",
      specslist: "specs/getList",
      goodslist: "goods/getGoods",
      count: "goods/getCount"
    })
  },
  props: ["info"],
  methods: {
    ...mapActions({
      getCate: "cate/getCateAction",
      getSpecs: "specs/getSpecsActions",
      getGoods: "goods/getGoodsAction",
      getCount: "goods/getCountAction"
    }),
    //富文本编辑器：
    openEvent() {
      this.editor = new E("#editor");
      this.editor.create();
      this.editor.txt.html(this.goodsinfo.description)
    },
    changeCate(n) {
      // let index = this.catelist.findIndex((item,i)=>{
      //   return item.id == this.goodsinfo.first_cateid;
      // })
      // console.log(index)
      let index = this.catelist.findIndex(
        item => item.id == this.goodsinfo.first_cateid
      );
      this.secondArr = this.catelist[index].children;
      if (!n) {
        this.goodsinfo.second_cateid = "";
      }
    },
    changeSpecs(n) {
      let index = this.specslist.findIndex(
        item => item.id == this.goodsinfo.specsid
      );
      this.specsArr = this.specslist[index].attrs;
      if (!n) {
        this.goodsinfo.specsattr = [];
      }
    },
    //图片
    onpreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onremove() {
      console.log(file, "移除", filelist);
    },
    onchange(file, filelist) {
      console.log(file, 8888);
      console.log(filelist, 888899999);
      console.log(file, "文件详情，change时候");
      this.goodsinfo.img = file.raw;
    },
    cancel() {
      this.$emit("cancel", false);
      this.reset();
      this.editor.destroy()
    },
    reset() {
      this.goodsinfo = {
        roleid: 0,
        username: "",
        password: "",
        status: 1
      };
    },
    //数据回显：
    lookup(id) {
      goodsinfo({ id }).then(res => {
        if (res.code == 200) {
          this.goodsinfo = res.list;
          this.goodsinfo.id = id;
          //图片回显：
          this.filelist = this.goodsinfo.img
            ? [{ url: this.$http + this.goodsinfo.img }]
            : [];
          this.goodsinfo.specsattr = this.goodsinfo.specsattr.split(",");
          this.changeCate(true);
          this.changeSpecs(true);
        }
      });
    },
    //封装一个确定事件
    confirm() {
      this.$refs.goods.validate(val => {
        if (val) {
          console.log(this.goodsinfo, 333);
           this.goodsinfo.specsattr = this.goodsinfo.specsattr.join(",");
          this.goodsinfo.description = this.editor.txt.html()
          //验证成功之后，分别调用添加或者编辑接口
          //添加
          if (this.info.isAdd) {
            goodsadd(this.goodsinfo).then(res => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getSpecs();
                //重新渲染
                this.getGoods();
                //调用总条数
                this.getCount();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            goodsedit(this.goodsinfo).then(res => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.cancel();
                this.getGoods();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    }
  },
  mounted() {
    if (this.catelist.length == 0) {
      this.getCate();
    }
    if (this.catelist.length == 0) {
      this.getSpecs();
    }
  }
};
</script>

<style  scoped>
</style>
